package com.lanyanhua.job.job;

import com.alibaba.fastjson.JSON;
import com.lanyanhua.job.entity.*;
import com.lanyanhua.job.service.IEmailService;
import com.lanyanhua.job.service.IJobLogService;
import com.lanyanhua.job.utils.DateUtils;
import com.lanyanhua.job.utils.EmailUtils;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.web.client.RestTemplate;

import static org.apache.commons.lang3.exception.ExceptionUtils.*;

/**
 * @Auther: lanyanhua
 * @Date: 2018/10/17 0017 14:45
 * @Description:
 */
@Slf4j
public class ExecuteJob implements Job {

    protected static RestTemplate restTemplate ;
    protected static IEmailService emailService ;
    protected static IJobLogService jobLogService;
    protected static EmailUtils emailUtils ;
    protected JobInfo jobInfo ;
    private int i = 0;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        log.info("进入了---testJob : " + ++i);
        JobDataMap param = jobExecutionContext.getMergedJobDataMap();
        jobInfo = (JobInfo) param.get("jobInfo");
        String subject = "项目：" + jobInfo.getJobGroup() + ",执行任务：" + jobInfo.getJobName();
        JobLog jobLog = new JobLog(jobInfo);
        log.info("id:" + jobInfo.getJobId() + "," + subject);
        Result result = executeCall();
        subject += result.getMessage();
        jobLog.end(result);
        try {
            jobLogService.save(jobLog);
        } catch (Exception e) {
            log.error(subject + "报错日志失败！！！" + getStackTrace(e));
        }
        try {
            if (isSend()) {
                EmailServerInfo emailServerInfo = emailService.findById(jobInfo.getEmailServerId()).get();
                EmailContent content = new EmailContent(subject, getEmailContent(jobLog));
                emailUtils.sendEmail(emailServerInfo, content);
            }
        } catch (Exception e) {
            log.error("发送邮箱报错！！" +  getStackTrace(e));
        }
        log.info("执行完成~");
    }

    /**
     * 初始化数据
     */
    public static void init(RestTemplate restTemplate,IEmailService emailService,IJobLogService jobLogService){
        ExecuteJob.emailService = emailService;
        ExecuteJob.emailUtils = new EmailUtils();
        ExecuteJob.jobLogService = jobLogService;
        ExecuteJob.restTemplate = restTemplate;
    }
    /**
     * 调用 定时任务url连接地址 负载均衡就重写这个方法
     */
    public Result executeCall(){
        try {
            Result result = restTemplate.getForObject(jobInfo.getExecuteAddress(), Result.class);
            if (result != null && result.isSuccess()) {
                log.info("执行成功：result" + JSON.toJSONString(result));
                return new Result(true,"200","执行成功！！");
            } else {
                log.error("执行失败：result:" + JSON.toJSONString(result));
                return new Result(false,"500","执行失败，请尽快处理！！！");
            }
        } catch (Exception e) {
            log.error( "执行时出现异常：" + getStackTrace(e));
            return new Result(false, "500", "执行时出现异常");
        }
    }

    /**
     * 是否发送 默认是存在邮箱就发送
     */
    public boolean isSend(){
        return jobInfo.getEmailServerId() != null;
    }

    /**
     *  邮箱发送内容
     */
    public String getEmailContent(JobLog jobLog){
        return "index:" + i +
                "执行地址：t" + jobLog.getExecuteAddress() + "\r\n" +
                "cron表达式：" + jobLog.getCronExpression() + "\r\n" +
                "开始执行时间：" + DateUtils.getStringDate("yyyy-MM-dd hh:mm:ss", jobLog.getStartTime()) + "\r\n" +
                "结束时间：" + DateUtils.getStringDate("yyyy-MM-dd hh:mm:ss", jobLog.getEndTime()) + "\r\n" +
                "执行结果：" + jobLog.isSuccess() + "\r\n" +
                "错误状态码：" + jobLog.getErrorCode() + "\r\n" +
                "消息：" + jobLog.getMessage() + "\r\n";
    }

}
